<?php

class UserActivityBadgesController extends MainController implements ControllerInterface {

	//o - order
	//v - order vector
	//t - total items to select
	public $tableConfig = array(
		'user_badges_table' => array(
			'o' => array(
				'id' => 'id_user_activity_badges',
				'badge' => 'badge',
				'points' => 'points',
				'_' => 'id'
			),
			'v' => 'malejaco',
			't' => 10
		),
		'dict_actions_table' => array(
			'o' => array(
				'id' => 'id_dict_actions',
				'active' => 'active',
				'name' => 'name',
				'description' => 'description',
				'_' => 'id'
			),
			'v' => 'malejaco',
			't' => 10
		),
	);

	public function preDispatch($param) {
		$this->RunShared('Auth');
		$this->Run($param);
	}

	public function postDispatch($param) {
		
	}

	public function IndexAction($param) {
		$dalObj = UserActivityBadgesDAL::GetDalDataObj(
						array(
							'tableData' => $this->tableParams['user_badges_table'],
							'join' => array(
								'DictActions' => ' LEFT JOIN dict_actions ON dict_actions.id_dict_actions = user_activity_badges.id_dict_actions'
							)
						)
		);
		$arrData = UserActivityBadgesDAL::GetResult($dalObj);

		$this->smarty->assign('arrData', $arrData);
	}

	public function EditAction($param) {
		$id = isset($param['id']) ? $param['id'] : -1;

		if (Request::IsPost()) {
			$this->Save($id);
		}

		$dalObj = UserActivityBadgesDAL::GetDalDataObj(
						array(
							'tableData' => $this->tableParams['user_badges_table'],
						)
		);
		$dalObj->addCondition('id_user_activity_badges', $id);

		$arrData = UserActivityBadgesDAL::GetResult($dalObj);

		if (!empty($arrData)) {
			$arrData = $arrData[0];
			$title = 'Edytuj';
		} else {
			$arrData = new UserActivityBadges(-1);
			$title = 'Nowy';
		}
		$arrDictActions = $this->GetDictActions();

		$this->smarty->assign('title', $title);
		$this->smarty->assign('arrData', $arrData);
		$this->smarty->assign('arrDictActions', $arrDictActions);
	}

	private function GetDictActions() {
		$dalData = DictActionsDAL::GetDalDataObj(
						array(
							'tableData' => $this->tableParams['dict_actions_table'],
							'limit' => 100
						)
		);

		$arrData = DictActionsDAL::GetResult($dalData);

		return $arrData;
	}

	private function Save($id) {
		$arrData = array(
			'badge' => Request::GetPost('badge'),
			'points' => Request::GetPost('points')
		);

		$errors = $this->ValidateSaveAction(array('validation_data' => $arrData), false);
		if (empty($errors)) {
			$activityBadge = new UserActivityBadges();
			$activityBadge->setId($id);
			$activityBadge->setBadge($arrData['badge']);
			$activityBadge->setPoints($arrData['points']);
			$activityBadge->setIdDictActions(Request::GetPost('dict-actions'));
			if($id == -1)$activityBadge->setGroup('NULL');

			if(Request::Check('removeImage')) {
				$activityBadge->setImage('');
			}
			if(isset($_FILES['image']) && is_uploaded_file($_FILES['image']['tmp_name'])) {
				
				$dir = PATH_STATIC_CONTENT . 'upload/badges';

				if(!is_dir($dir))
					mkdir ($dir, 0777);

				$filename = md5(microtime()).'.'.array_pop(explode('.',$_FILES['image']['name']));

				if(move_uploaded_file($_FILES['image']['tmp_name'], $dir.'/'.$filename)) {
					$activityBadge->setImage('/upload/badges/'.$filename);
				}
			}
			

			UserActivityBadgesDAL::Save($activityBadge->GetDalDataObj());
			return $this->AddRedirect(Router::GenerateUrl('UserActivityBadgesIndex', array('UserActivityBadges' => 'Index')), 0);
		} else {
			$data = array();
			foreach ($errors AS $row) {
				$data[$row['field']] = $row['value'];
				$errors_data[$row['field']] = $row['msg'];
			}
			$this->smarty->assign('arrPostData', $data);
			$this->smarty->assign('errors_data', $errors_data);
		}
	}

	public function ValidateSaveAction($param, $as_action = true) {
		if ($as_action)
			$this->SetValidatorRender();
		$validator = new Validator(isset($param['validation_data']) ? $param['validation_data'] : array());

		$validator->IsEmpty('badge', 'Musisz podać nazwe rangi');
		$validator->IsEmpty('points', 'Musisz podać wymaganą liczbę punktów');
		$validator->IsNumber('points', 'To musi być liczba całkowita');

		$this->smarty->assign('js_values', $validator->getJsValues());
		$this->smarty->assign('id_form', Request::GetGet('id_f'));
		return $validator->getErrorList();
	}

	public function DeleteAction($param) {
		$this->setNoRender();


		$obj = UserActivityBadgesDAL::GetResult(
						UserActivityBadgesDAL::GetDalDataObj(
								array(
									'condition' => array(
										'id' => array($param['id'])
									)
								)
						)
		);

		if (!isset($obj[0])) {
			return $this->AddRedirect(Router::GenerateUrl('UserActivityBadgesIndex', array('UserActivityBadges' => 'Index')), 0);
		}
		$obj = $obj[0];

		UserActivityBadgesDAL::DefaultDelete($obj->GetDalDataObj());

		$this->AddRedirect(Router::GenerateUrl('UserActivityBadgesIndex', array('UserActivityBadges' => 'Index')), 0);
	}


	public function GroupAction($param) {
		$this->setNoRender();

		if(Request::IsPost()) {
			$data = Request::GetAllPost();

			if(isset($data['groupName']) && strlen($data['groupName']) > 0 && isset($data['group'])) {
				$sql = 'UPDATE user_activity_badges SET `group` = "'.mysql_real_escape_string($data['groupName']).'" WHERE id_user_activity_badges IN ('.implode(',',$data['group']).')';
				Registry::Get('db')->prepare($sql)->execute();

				$this->addRedirectInfo('Poprawnie zgrupowano','ok',Router::Generateurl('usAcBa',array('UserActivityBadges' => 'Index')),0);
			}else{
				$this->addRedirectInfo('Wystąpił błąd podczas grupowania','err',Router::Generateurl('usAcBa',array('UserActivityBadges' => 'Index')),0);
			}
		}else{
			$this->addRedirectInfo('Wystąpił błąd podczas grupowania','err',Router::Generateurl('usAcBa',array('UserActivityBadges' => 'Index')),0);
		}
	}

	public function UngroupAction($param) {
		$this->setNoRender();

		$sql = 'UPDATE user_activity_badges SET `group` = NULL WHERE id_user_activity_badges IN ('.$param['id'].')';
		Registry::Get('db')->prepare($sql)->execute();

		$this->addRedirectInfo('Poprawnie rozgrupowano','ok',Router::Generateurl('usAcBa',array('_value' => 'UserActivityBadges')),0);
	}
}

?>